package ruc.TDEngine.write;

import okhttp3.Response;
import ruc.Consts.constant;
import ruc.utils.IOUtils;
import ruc.TDEngine.TDEngine_Common;

import java.io.IOException;

public class TDEngine_MultiTableWrite {
    private String IP, port, dbName, tbName,userName,password;

    public TDEngine_MultiTableWrite(String IP, String port, String dbName, String tbName, String userName, String password) {
        this.IP = IP;
        this.port = port;
        this.dbName = dbName;
        this.tbName = tbName;
        this.userName = userName;
        this.password = password;
    }

     private void insert(String[] values, int[] tableNum) throws IOException {
        int idx = 0;
        String sql = "insert into";
        // create all table at once
        for(int i = 0; i < tableNum[tableNum.length - 1]; i++) {
            TDEngine_Common.createTable(IP, port, dbName, tbName+i, userName, password); //创建新表
        }

        int[] cnt = new int[tableNum.length];
        while(idx < values.length) {
            for(int i = 0; i < tableNum.length; i++) {
                StringBuilder sb = new StringBuilder();
                for(int j = 0; j < tableNum[i]; j++) {
                    if (idx == values.length) {
                        System.out.printf("[TSBench-D] >>>>>>>> index out of bounds, the length of array:%d >>>>>>>>>>>> \n", values.length);
                        break;
                    }
                    sb.append(String.format(" %s.%s", dbName, tbName)).append(j);
                    String[] t = values[idx++].split(constant.Delimiter);
                    sb.append(String.format(" values(%s,\"%s\",\"%s\",\"%s\",%s, %s, %s)", t[0], t[1], t[2], t[3], t[4], t[5], t[6]));
                }

                String tmp = sql + sb;
                long st_Time = System.nanoTime();
                //batch insert
                Response response = TDEngine_Common.send(TDEngine_Common.getRequest(tmp, userName, password, IP, port));
                assert response != null;
                response.close();

                cnt[i] += (System.nanoTime() - st_Time) / constant.Ns2Ms;
            }
        }

        for(int i = 0; i < cnt.length; i++) {
            System.out.printf("[TSBenchD] [TDEngine_MultiTableWrite] >>>>> tableNum：%d, costTime：%d >>>>> \n", tableNum[i], cnt[i]);
            IOUtils.WriteData(constant.GetWriteFilePath("TDEngine", "MultiTableWrite"),
                    new String[]{String.valueOf(tableNum[i]), String.valueOf(cnt[i])});
        }
    }

    public static void main(String[] args) throws IOException {
        TDEngine_MultiTableWrite db = new TDEngine_MultiTableWrite(constant.IP, constant.TDEngine_port, constant.dbName, constant.MultiTableWrite_tbName, constant.userName, constant.passWord);
        db.insert(IOUtils.GetData(), constant.MutiTable_TableNum);
    }
}
